$(function(){
	var delParent;
	var defaults = {
		fileType         : ["jpg","png","bmp","jpeg","mp4"],   // 上传文件的类型
		fileSize         : 1024 * 1024 * 100                  // 上传文件的大小 10M
	};
		/*点击图片的文本框*/
	$(".file").change(function(){
		// debugger;
		var $fatherId=$(this).parents('section.img-section').find('input.getvalue');
		var limit =$(this).parents('section.img-section').data('limit');
		var idFile = $(this).attr("id");
		var file = document.getElementById(idFile);
		var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
		var fileList = file.files; //获取的图片文件
		var input = $(this).parent();//文本框的父亲元素
		var imgArr = [];
		//遍历得到的图片文件
		var numUp = imgContainer.find(".up-section").length;
		var totalNum = numUp + fileList.length;  //总的数量
		if(fileList.length > limit || totalNum > limit ){
            $.modal.msgWarning("上传图片数目不可以超过"+limit+"张，请删除重新选择");
            return;
		}
		else if(numUp < limit){
			fileList = validateUp(fileList);
            const region = 'oss-cn-shenzhen';//'http://recruitapp.oss-cn-shenzhen.aliyuncs.com';
            const accessId = 'LTAIvXI5X6vRf3k0';
            const accessKey = '4nG1pSZAoMvvN4X4nLtaUarfPkNGO2';
            const bucket = 'recruitapp';
		  const client = new OSS.Wrapper({
			region: region,
			accessKeyId: accessId,
			accessKeySecret: accessKey,
			bucket: bucket
		  });
		  	var position = 0;
            for(var i = 0;i<fileList.length;i++){
		  const type = file.files[i].type.split('/')[0];
		  const size = file.files[i].size;
		  const storeAs = '/datas/file/' + new Date().getTime() + '.' + file.files[i].name.split('.').pop();
		  console.log(storeAs, 'storeAs');
			var imgUrl = window.URL.createObjectURL(fileList[i]);
			imgArr.push(imgUrl);
			var $section = $("<section class='up-section fl loading' >");
			imgContainer.prepend($section);
			var $span = $("<span class='up-span'>");
			$span.appendTo($section);

			var $img0 = $("<img class='close-upimg'>").on("click",function(event){
				event.preventDefault();
				event.stopPropagation();
				$(".works-mask").show();
				delParent = $(this).parent();
			});
			$img0.attr("src",$("#staticUrl").val()+"/img/a7.png").appendTo($section);
			var $img = $("<img class='up-img up-opcity' index='"+i+"'>");
			$img.appendTo($section);
			var $p = $("<p class='img-name-p'>");
			$p.html(fileList[i].name).appendTo($section);
			// var $input = $("<input id='taglocation' name='taglocation' value='' type='hidden'>");
			// $input.appendTo($section);
			// var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
			// $input2.appendTo($section);
		  client.multipartUpload(storeAs, file.files[i]).then(function (results) {
                  var url;
                  var imgurl= imgContainer.find("section:eq("+position+") .up-img");
                  position++;
                  if (size >= 100 * 1024) {
                      if($fatherId.val()!=""&&$fatherId.val().indexOf(undefined)==-1){
                          url=results.res.requestUrls[0].split('?')[0];
                      }else{
                          url=results.res.requestUrls[0].split('?')[0];
                      }
                      console.log(results.res.requestUrls[0].split('?')[0], 'results');
                      imgurl.attr("src",results.res.requestUrls[0].split('?')[0]);
                      $fatherId.val(url);
                  } else {
                      if($fatherId.val()!=""&&$fatherId.val().indexOf(undefined)==-1){
                          url=results.url;
                      }else{
                          url=results.url;
                      }
                      console.log(results, 'results');
                      imgurl.attr("src",results.url);
                      $fatherId.val(url);
                  }
                  $(".up-section").removeClass("loading");
                  $(".up-img").removeClass("up-opcity");
                  $fatherId.trigger('back');
		  });
            }
		}
		 numUp = imgContainer.find(".up-section").length;
		if(numUp >= limit){
			$(this).parent().hide();
		}
	});



    $(".z_photo").delegate(".close-upimg","click",function(){
        var $fatherId=$(this).parents('section.img-section').find('input.getvalue');
        var imgArry=$fatherId.val().split(",");
        var delUrl=$(this).next().attr("src");
        var fileUrl;
        for(var i = 0;i<imgArry.length;i++){
            if(delUrl==imgArry[i]){
			}else{
            	if(fileUrl!=""){
                    fileUrl=fileUrl+","+imgArry[i];
                }else{
                    fileUrl=imgArry[i];
				}
			}
        }
        $fatherId.val(fileUrl);
     	  $(".works-mask").show();
     	  delParent = $(this).parent();
	});

	$(".wsdel-ok").click(function(){
		$(".works-mask").hide();
        var limit =delParent.parents('section.img-section').data('limit');
		var numUp = delParent.siblings().length;
		if(numUp < limit){
			delParent.parent().find(".z_file").show();
		}
      	var $input= delParent.parents('section.img-section').find('input.getvalue');
       	var src= delParent.find('.up-img').attr('src');
		 if($input){
            if($input.val()){
                var url= '';
                $.each($input.val().split(','),function (index, item) {
                    if(item!==src){
                        if(url!==''){
                            url=url+','+item;
                        }else {
                            url=item;
                        }
                    }
                });
                $input.val(url);
            }
		 }
		delParent.remove();

	});

	$(".wsdel-no").click(function(){
		$(".works-mask").hide();
	});

		function validateUp(files){
			var arrFiles = [];//替换的文件数组
			for(var i = 0, file; file = files[i]; i++){
				//获取文件上传的后缀名
				var newStr = file.name.split("").reverse().join("");
				if(newStr.split(".")[0] != null){
						var type = newStr.split(".")[0].split("").reverse().join("");
						console.log(type+"===type===");
						if(jQuery.inArray(type, defaults.fileType) > -1){
							// 类型符合，可以上传
							if (file.size >= defaults.fileSize) {
								alert(file.size);
								alert('您这个"'+ file.name +'"文件大小过大');
							} else {
								// 在这里需要判断当前所有文件中
								arrFiles.push(file);
							}
						}else{
							alert('您这个"'+ file.name +'"上传类型不符合');
						}
					}else{
						alert('您这个"'+ file.name +'"没有类型, 无法识别');
					}
			}
			return arrFiles;
		}
})
